package com.markerhub.exception;

import com.markerhub.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;

/*
* 全局异常处理
* */
@Slf4j
@RestControllerAdvice
public class GlobalExcepitonHandler {

    //捕捉其他异常
    @ResponseStatus(HttpStatus.BAD_REQUEST) //400
    @ExceptionHandler(value = RuntimeException.class)
    public Result handler(RuntimeException r) {
        log.error("运行时异常",r);
        return Result.error(r.getMessage());
    }

    //shiro抛出的异常，比如没有权限，用户登录异常
    @ResponseStatus(HttpStatus.UNAUTHORIZED) //401
    @ExceptionHandler(value = ShiroException.class)
    public Result handler(ShiroException r) {
        log.error("运行时异常",r);
        return Result.error(401,r.getMessage(),null);
    }

    /**
     * @Validated 校验错误异常处理
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e) throws IOException {
        log.error("运行时异常:-------------->",e);
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return Result.error(objectError.getDefaultMessage());
    }

    /**
     * 处理Assert的异常
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e) throws IOException {
        log.error("Assert异常:-------------->{}",e.getMessage());
        return Result.error(e.getMessage());
    }

}
